package com.xclink.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	// 声明一个静态变量url
	private static String url;
	// 多文件上传
	public static String uploadFiles(MultipartFile[] files, String webpath) throws IOException {

		if (files != null && files.length > 0 && files[0].getSize() > 0) {
			StringBuffer urls = new StringBuffer();
			for (MultipartFile file : files) {
				String url = uploadFile(file, webpath);
				url = url + ",";
				urls.append(url);
			}
			//System.out.println("上传的文件路径============" + urls);
			return urls.toString();
		} else {
			return null;
		}
	}

	/**
	 * 单文件上传
	 * 
	 * @param file
	 *            文件上传的控件名字
	 * @param webpath
	 *            文件上传的根路径
	 * @return
	 * @throws IOException
	 */
	public static String uploadFile(MultipartFile file, String webpath) throws IOException {
		//System.out.println("单文件上传");
		// 文件夹的名字
		String mk = "/files/";
		if (file != null && file.getSize() > 0) {
			// 记录文件上传的开始时间
			long startTime = System.currentTimeMillis();
			// 上传文件的名称（包含后缀名）
			String filename = file.getOriginalFilename();
			// 获取的文件后缀名
			String suffixname = FilenameUtils.getExtension(filename);
//			if (suffixname.equalsIgnoreCase("jpg") || suffixname.equalsIgnoreCase("png")|| suffixname.equalsIgnoreCase("jpeg")) {
//				mk = "/image/";
//			} else if (suffixname.equalsIgnoreCase("doc") || suffixname.equalsIgnoreCase("docx")||suffixname.equalsIgnoreCase("pdf")||suffixname.equalsIgnoreCase("txt")) {
//				mk = "/doc/";
//			} else {
//				mk = "/files/";
//			}
			int a = (int) (Math.random() * 100);
			String b = String.valueOf(a);
			filename = Long.toString(startTime) + b + "." + suffixname;
			
			String filePath = webpath + mk;
			// 上传文件存放的路径的父目录，如果不存在，就创建一次
			File deskFile = new File(filePath, filename);
			File parentFile = deskFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			// 文件上传
			file.transferTo(deskFile);
			// 记录文件上传的结束时间
			// long endTime = System.currentTimeMillis();
			// 传输文件一共耗时多少毫秒
			// long time =endTime-startTime;
			// System.out.println("上传文件耗时毫秒数："+time);
			url = mk + filename;
		} else {
			url = null;
		}
		return url;

	}

	// 删除上传的文件，返回true或者false
	public static boolean deleteFile(String fileName, String webpath) {
		// 应用所在的路径+"/"或者"\"+"upload"
		// 注意：：： 这个不能写在这里，需要写在调用的方法里
		// String
		// webpath=request.getSession().getServletContext().getRealPath("")+File.separator+"upload";
		fileName = webpath + fileName;
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			// System.out.println("删除单个文件失败：" + fileName + "不存在！");
			return false;
		}
	}
	
//文件下载
	// url文件的绝对路径
		public static void downloadFile(String url, String name, HttpServletRequest request, HttpServletResponse response) {
			// String webpath = request.getSession().getServletContext().getRealPath("") + File.separator + "upload/";
			// 取得文件的文件名加后缀名。
			// String name = url.substring(url.lastIndexOf("/") ,url.lastIndexOf(""));
			// 文件的绝对路径(斜杠截取会出现乱码暂且不用)
			try {
				execute(request, response, url, name);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public static void execute(HttpServletRequest request, HttpServletResponse response, String fileAbsPath,
				String showName) throws Exception {
			execute(request, response, new File(fileAbsPath), showName);
		}

		public static void execute(HttpServletRequest request, HttpServletResponse response, File file, String showName)
				throws Exception {
			execute(request, response, new FileInputStream(file), file.length(), showName);
		}

		public static void execute(HttpServletRequest request, HttpServletResponse response, InputStream input, long length,
				String showName) throws Exception {
			String info = request.getHeader("User-Agent").toLowerCase();
			if (info.contains("firefox")) { // Firefox
				showName = new String(showName.getBytes(), "ISO-8859-1");
			} else { // IE,Chrome
				showName = URLEncoder.encode(showName, "UTF-8");
			}

			response.reset(); // 响应重置
			response.setHeader("Content-Disposition", "attachment; filename=\"" + showName + "\"");
			// response.addHeader("Content-Length", ""+length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream out = response.getOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024 * 8];
			while ((len = input.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			input.close();
			out.close();
			response.flushBuffer();
		}

}
